package com.mexico.inloancash;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustAttribution;
import com.adjust.sdk.AdjustConfig;
import com.adjust.sdk.LogLevel;
import com.adjust.sdk.OnAttributionChangedListener;
import com.adjust.sdk.OnDeviceIdsRead;
import com.appsflyer.AppsFlyerConversionListener;
import com.appsflyer.AppsFlyerLib;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.mexico.inloancash.utils.MyPreferencesManager;

import java.util.ArrayList;
import java.util.Map;

import ai.advance.liveness.lib.GuardianLivenessDetectionSDK;
import ai.advance.liveness.lib.Market;

import static com.facebook.FacebookSdk.setAdvertiserIDCollectionEnabled;
import static com.facebook.FacebookSdk.setAutoLogAppEventsEnabled;

public class MyApplication extends Application {

    public static MyApplication application;

    public static ArrayList<Activity> list = new ArrayList<Activity>();

    public static final String INDIAKEY="aab0194fb8f86e84";

    // public static String source = "yx";

    public static String source = "mao";

    //public static String source = "Google";

    //public static String source = "DSZL";

    //public static String source = "message";

    //public static String source = "CC";

    //public static String source = "XH";

    private static final String AF_DEV_KEY = "DAYBvfRejUEctWAFYgris9";

    public static final String ADJUST_APP_TOKEN = "zrcedhygmqkg";

    private static MyApplication instance;

    public static MyApplication getApplication(){
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance=this;
        AppsFlyerLib.getInstance().init(AF_DEV_KEY, conversionListener, getApplicationContext());
        AppsFlyerLib.getInstance().startTracking(this);
        String environment = AdjustConfig.ENVIRONMENT_PRODUCTION;

        AdjustConfig config = new AdjustConfig(this, ADJUST_APP_TOKEN, environment);
        config.setLogLevel(LogLevel.VERBOSE);


        //faceBook===================================================
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);

        //上线要注释掉
        //FacebookSdk.setIsDebugEnabled(true);
        //FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS);

        setAutoLogAppEventsEnabled(true);//开启事件记录
        setAdvertiserIDCollectionEnabled(true);//启用收集

        //faceBook===================================================

        config.setNeedsCost(true);
        config.setOnAttributionChangedListener(new OnAttributionChangedListener() {
            @Override
            public void onAttributionChanged(AdjustAttribution attribution) {
                if(attribution!=null){
                    if(!TextUtils.isEmpty(attribution.trackerName)){
                        //归因回传  这个回调一般在 首次激活时 会回调  保存渠道名 用于接口上传(每次卸载掉应用 重新安装 都会回调一次  adjust那边技术说的 有待观察)
                        MyPreferencesManager.putTrackerName(attribution.trackerName);
                        //Toast.makeText(MyApplication.this,"MyApplication onCreate"+attribution.trackerName,Toast.LENGTH_LONG).show();
                    }
                }
            }
        });


        Adjust.onCreate(config);
        registerActivityLifecycleCallbacks(new AdjustLifecycleCallbacks());

        MyPreferencesManager.initPreferencesManager(this);
        //TODO 面部识别初始化
        GuardianLivenessDetectionSDK.init(this, BuildConfig.LivenessAccessKey, BuildConfig.livenessSecretKey, Market.Mexico);
        //初始化Firebase
//        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        Adjust.getGoogleAdId(this, new OnDeviceIdsRead() {
            @Override
            public void onGoogleAdIdRead(String googleAdId) {
            }
        });
        //在这里获取手机信号强度
        getMobileNetworkSignal();
    }

   public static String mobileNetworkSignal = "";

    private void getMobileNetworkSignal() {
        try {
            TelephonyManager mTelephonyManager = (TelephonyManager) MyApplication.getApplication().getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
            if (mTelephonyManager != null) {
                mTelephonyManager.listen(new PhoneStateListener() {
                    @Override
                    public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                        super.onSignalStrengthsChanged(signalStrength);
                        int asu = signalStrength.getGsmSignalStrength();
                        int lastSignal = -113 + 2 * asu;
                        if (lastSignal > 0) {
                            mobileNetworkSignal = lastSignal + "dBm";
                            //Log.e("data", "当前信号强度：" + lastSignal + " dBm");
                            mTelephonyManager.listen(this, PhoneStateListener.LISTEN_NONE);//移除监听
                        }

                    }
                }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static MyApplication getInstance() {
        if (application == null) {
            application = new MyApplication();
        }
        return application;
    }

    AppsFlyerConversionListener conversionListener = new AppsFlyerConversionListener() {


        @Override
        public void onConversionDataSuccess(Map<String, Object> conversionData) {

            for (String attrName : conversionData.keySet()) {
                Log.d("LOG_TAG1", "attribute: " + attrName + " = " + conversionData.get(attrName));
            }
        }

        @Override
        public void onConversionDataFail(String errorMessage) {
            Log.d("LOG_TAG", "error getting conversion data: " + errorMessage);
        }

        @Override
        public void onAppOpenAttribution(Map<String, String> conversionData) {

            for (String attrName : conversionData.keySet()) {
                Log.d("LOG_TAG", "attribute: " + attrName + " = " + conversionData.get(attrName));
            }

        }

        @Override
        public void onAttributionFailure(String errorMessage) {
            Log.d("LOG_TAG", "error onAttributionFailure : " + errorMessage);
        }
    };

    public void removeActivity(Activity a) {
        // TODO Auto-generated method stub
        list.remove(a);
    }

    public void addActivity(Activity a) {
        // TODO Auto-generated method stub
        list.add(a);
    }

    public void finishActivity() {
        // TODO Auto-generated method stub
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
        list.clear();
    }

    private static final class AdjustLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {

        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {
            Adjust.onResume();
        }

        @Override
        public void onActivityPaused(Activity activity) {
            Adjust.onPause();
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {

        }
    }
}
